package com.chuji.crmcj.adapter;

import android.app.Activity;
import android.app.AlertDialog;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.text.TextUtils;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.chuji.crmcj.R;
import com.chuji.crmcj.bean.FollDataInfo;
import com.chuji.crmcj.utils.UIUtils;

import java.util.List;

/**
 * Created by Administrator on 2016/3/16 0016.
 */
public class MagLineAdapter extends BaseAdapter implements MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnPreparedListener {
    private Activity mActivity;
    private List<FollDataInfo.ApiParamObjEntity> follDataInfo;
    private ViewHolder holder;
    private int lable;
    private TextView mTvConnType;
    private MediaPlayer mediaPlayer = null;
    private SeekBar mSb_detail_play_progress;
    private TextView mTv_play_time;
    private TextView mTv_total_time;
    //播放录音
    private ImageButton mBtn_play;
    private int goOrPause = 0;
    private int taskType;
    private String content;
    private String taskTypeContent;
    private String taskTypeDetail;
    private TextView tv_time;
    private TextView tv_old_note;
    private int isComplete;
    private ImageView ll_cancel;

    public MagLineAdapter(Activity mActivity, List<FollDataInfo.ApiParamObjEntity> follDataInfo, int lable) {
        this.mActivity = mActivity;
        this.follDataInfo = follDataInfo;
        this.lable = lable;
    }

    @Override
    public int getCount() {
        return follDataInfo.isEmpty() ? 0 : follDataInfo.size();
    }

    @Override
    public Object getItem(int i) {
        return follDataInfo.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public int getItemViewType(int position) {
        return super.getItemViewType(position);
    }

    @Override
    public int getViewTypeCount() {
        return super.getViewTypeCount();
    }

    StringBuffer buffer = new StringBuffer();

    @Override
    public View getView(final int position, View view, ViewGroup viewGroup) {
        if (view == null) {
            holder = new ViewHolder();
            view = View.inflate(mActivity, R.layout.item_follow_timeline, null);
            holder.mIvEditItem = (ImageView) view.findViewById(R.id.iv_edit_item);
            holder.mTvConTime = (TextView) view.findViewById(R.id.tv_connection_time);
            holder.mTvConBody = (TextView) view.findViewById(R.id.tv_detail_type);
            holder.mTvConType = (TextView) view.findViewById(R.id.tv_connections_type);
            holder.mTvRemark = (TextView) view.findViewById(R.id.tv_remark);
            holder.mIvListener = (ImageView) view.findViewById(R.id.iv_listener);
            view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();
        }
        taskTypeContent = follDataInfo.get(position).getTaskTypeContent();
        taskType = follDataInfo.get(position).getTaskType();
        if (taskType == 6) {
            holder.mTvConType.setText(taskTypeContent);
        } else {
            content = follDataInfo.get(position).getAttachment();
            taskTypeDetail = follDataInfo.get(position).getTaskDetail();

            //经理端的浅客和保客 都能听录音
            if (taskType == 1 || taskType == 5) {
                holder.mIvListener.setVisibility(View.VISIBLE);
            }
            if (taskType == 0) {
                //上门
                holder.mTvConBody.setText(follDataInfo.get(position).getTaskDetail().toString());
            } else if (taskType == 1) {
                //电话
                holder.mTvConBody.setText(follDataInfo.get(position).getTaskDetail());
            } else if (taskType == 2) {
                //短信
                if (!TextUtils.isEmpty(content) && !content.isEmpty()) {
                    holder.mTvConBody.setText(content);
                }
            } else if (taskType == 3) {
                // QQ 微信等上门
//            if (!TextUtils.isEmpty(content)) {
//                holder.mTvConBody.setText(content);
//            }
                holder.mTvConBody.setText(taskTypeDetail);
            } else if (taskType == 4) {
                //不跟客户联系的记录  修改等级
                if (taskTypeContent.contains("成交")) {
                    String[] sourceStrArray = taskTypeDetail.split("\\|");
                    StringBuffer buffer = new StringBuffer();
                    for (int i = 1; i <= sourceStrArray.length; i++) {
                        if (i % 2 == 1) {
                            //奇数
                            buffer.append(sourceStrArray[i - 1] + "\t");
                        } else {
                            //偶数
                            buffer.append(sourceStrArray[i - 1] + "\n");
                        }
                    }
                    holder.mTvConBody.setText(buffer);
                } else {
                    holder.mTvConBody.setText(follDataInfo.get(position).getTaskDetail().toString());
                }
            } else if (taskType == 5) {
                //邀约来电
//            if (!TextUtils.isEmpty(content)) {
                holder.mTvConBody.setText(follDataInfo.get(position).getTaskDetail());
//            }
            }

            holder.mTvConTime.setText(follDataInfo.get(position).getCreateTime());
            holder.mTvConType.setText(taskTypeContent);

            holder.mIvListener.setOnClickListener(new View.OnClickListener()

                                                  {
                                                      @Override
                                                      public void onClick(View v) {
                                                          currentPostion = position;
                                                          showPlayRecorderDialog();
                                                      }
                                                  }

            );
        }
        return view;
    }

    public List<FollDataInfo.ApiParamObjEntity> getList() {
        return follDataInfo;
    }

    static class ViewHolder {
        private TextView mTvConBody;
        private ImageView mIvEditItem;
        private TextView mTvConTime;
        private TextView mTvConType;
        private ImageView mIvListener;
        private TextView mTvRemark;
    }

    //播放录音的dialog
    public void showPlayRecorderDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
        final AlertDialog dialog = builder.create();
        View view = View.inflate(mActivity, R.layout.dialog_play_recorder, null);// 给dialog设定特定布局
        // dialog.setView(view);
        dialog.setView(view, 0, 0, 0, 0);// 去掉上下左右边距, 兼容2.x版本
//        ImageView mIv_cancel = (ImageView) view.findViewById(R.id.iv_cancel);
        ll_cancel = (ImageView) view.findViewById(R.id.ll_cancel);
        mBtn_play = (ImageButton) view.findViewById(R.id.btn_play);
        mSb_detail_play_progress = (SeekBar) view.findViewById(R.id.sb_detail_play_progress);
        mTv_play_time = (TextView) view.findViewById(R.id.tv_play_time);
        mTv_total_time = (TextView) view.findViewById(R.id.tv_total_time);
        mSb_detail_play_progress.setEnabled(false);

        //播放进度条
        mSb_detail_play_progress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                                          boolean fromUser) {
                if (fromUser == true) {
                    mediaPlayer.seekTo(progress);
                    mTv_play_time.setText(ShowTime(progress));
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {


            }
        });

        //退出播放
        ll_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                mediaPlayer.stop();
            }
        });

        //点击播放
        mBtn_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (goOrPause == 0) {
                    play();
                    mTv_play_time.setText(ShowTime(mSb_detail_play_progress.getProgress()));
                    int Alltime = mediaPlayer.getDuration();
                    mTv_total_time.setText(ShowTime(Alltime));
                    goOrPause = 1;
                } else if (goOrPause == 1 || goOrPause == 2) {
                    pause();

                }
            }
        });
        dialog.show();
        WindowManager windowManager = mActivity.getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = (int) (display.getWidth()); //设置宽度
        dialog.getWindow().setAttributes(lp);
    }

    //当音乐播放时，每次按键时都会播放或者停止音乐
    private void pause() {
        //if(bt_pause.getText().toString().trim().equals("继续")){
        if (goOrPause == 2) {
            mediaPlayer.start();
            goOrPause = 1;
            mBtn_play.setBackgroundResource(R.drawable.zanting);
            return;
        } else if (goOrPause == 1) {
            if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
                goOrPause = 2;
                mBtn_play.setBackgroundResource(R.drawable.bofang);
            } else {
                UIUtils.showToastSafe("请先播放音频");
            }
        }
    }

    private int currentPostion;

    private void play() {

        try {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnBufferingUpdateListener(this);
            mediaPlayer.setOnPreparedListener(this);

            //todo 录音地址
//            mediaPlayer.reset();
//            FileInputStream fis = new FileInputStream("http://192.168.1.222:8088/UpLoads/SoundRecord/%E5%BC%A0%E8%B5%A2-%E6%9C%89%E9%92%B1%E7%9C%9F%E5%A5%BD[68mtv.com].mp4");
//            mediaPlayer.setDataSource(fis.getFD());

            mediaPlayer.reset();
            String attachment = follDataInfo.get(currentPostion).getAttachment();
            if (TextUtils.isEmpty(attachment)) {
                UIUtils.showToastSafe("录音地址为空");
            } else {
                mediaPlayer.setDataSource(attachment); // 设置数据源
            }
//            mediaPlayer.setDataSource("http://192.168.1.222:8088/UpLoads/SoundRecord/%E5%BC%A0%E8%B5%A2-%E6%9C%89%E9%92%B1%E7%9C%9F%E5%A5%BD[68mtv.com].mp4"); // 设置数据源

            mediaPlayer.prepare(); // prepare自动播放
//            mediaPlayer.prepareAsync();
            mediaPlayer.start();
            StrartbarUpdate();
            mSb_detail_play_progress.setMax(mediaPlayer.getDuration());
            mSb_detail_play_progress.setEnabled(true);
            mBtn_play.setBackgroundResource(R.drawable.zanting);
            //音乐播放时事件
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

                @Override
                public void onCompletion(MediaPlayer mp) {
                    mBtn_play.setEnabled(true);
                }
            });

            //出错时的事件
            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    mBtn_play.setEnabled(true);
                    return false;
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            UIUtils.showToastSafe("播放失败");
        }
    }

    //时间显示函数,我们获得音乐信息的是以毫秒为单位的，把把转换成我们熟悉的00:00格式
    private String ShowTime(int time) {
        time /= 1000;
        int minute = time / 60;
        int hour = minute / 60;
        int second = time % 60;
        minute %= 60;
        return String.format("%02d:%02d", minute, second);
    }

    Handler handler = new Handler();

    private void StrartbarUpdate() {
        handler.post(r);
    }

    Runnable r = new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            int CurrentPosition = mediaPlayer.getCurrentPosition();
            mTv_play_time.setText(ShowTime(CurrentPosition));
            mSb_detail_play_progress.setProgress(CurrentPosition);
            handler.postDelayed(r, 100);
        }
    };

    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {
        mSb_detail_play_progress.setSecondaryProgress(percent);
    }

    @Override
    public void onPrepared(MediaPlayer mp) {

    }

}